package com.simon.hotfix;

import android.app.Application;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.simon.hotfix.hotfix.HotFix;
import com.simon.hotfix.hotfix.HotFixUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

@SuppressWarnings("all")
public class MyApplication extends Application {
    private Handler mHandler = new Handler();

    @Override
    public void onCreate() {
        super.onCreate();

        HotFix.hotFix(this);

        // 初始化xUtils
        x.Ext.init(this);

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                queryFixFile();
            }
        }, 5000);
    }

    private void queryFixFile() {
        RequestParams params = new RequestParams("http://192.168.1.107:54321/dex/query");// + "?name=zhangsan"  107
        params.addHeader("token", "1234567890");

        x.http().request(HttpMethod.POST, params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i("Simon", "onSuccess = " + result);
                try {
                    JSONObject object = new JSONObject(result);
                    int code = object.getInt("code");
                    if (code == 200) {
                        JSONObject data = object.getJSONObject("data");
                        int version = data.getInt("version");
                        int dex_version = PreferencesUtil.getInt(getApplicationContext(), "DEX_VERSION", 0);
                        if (version > dex_version) {
                            downloadFixFile(version);
                        } else {
                            Toast.makeText(getApplicationContext(), "暂无热更新文件", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "获取热更新信息失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("Simon", "onError = " + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.i("Simon", "onCancelled");
            }

            @Override
            public void onFinished() {
                Log.i("Simon", "onFinished");
            }
        });
    }

    private void downloadFixFile(final int dex_version) {
        RequestParams params = new RequestParams("http://192.168.1.107:54321/dex/download");
        params.addHeader("token", "1234567890");

        final String saveFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/"+getPackageName()+"/files/dex_directory/classes_fix.dex";
        File fileDex = new File(saveFilePath);
        if (fileDex.exists()) {
            fileDex.delete();
            Log.i("Simon", "fileDex delete");
        }
        params.setSaveFilePath(saveFilePath);

        x.http().post(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(File result) {
                Log.i("Simon", "onSuccess = " + result.getPath());
                Toast.makeText(getApplicationContext(), "请稍后重启app", Toast.LENGTH_SHORT).show();
                PreferencesUtil.putInt(getApplicationContext(), "DEX_VERSION", dex_version);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //杀死整个进程
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }, 2500);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("Simon", "onError = " + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                Log.i("Simon", "onDownloadFinished");
            }

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                Log.i("Simon", "onLoading = " + (int) (current * 100 / total));
            }
        });

    }

}
